<?php

namespace Formax\CLI;

/**
 * 命令行模式参数管理
 */
class Args implements \ArrayAccess
{

    /**
     * @var \Phalcon\CLI\Dispatcher
     */
    public $dispatcher = null;

    /**
     * @param PhalconCLIDispatcher $dispatcher
     */
    public function __construct(\Phalcon\CLI\Dispatcher $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * 参数设置
     *
     * @param  string           $name
     * @param  mixed            $value
     * @return \Formax\CLI\Args
     */
    public function set($name, $value)
    {
        $this->dispatcher->setParam($name, $value);

        return $this;
    }

    /**
     * 获取参数
     *
     * @param  string $name
     * @param  mixed  $default
     * @return mixed
     */
    public function get($name, $default = null)
    {
        return $this->dispatcher->getParam($name, null, $default);
    }

    /**
     * 查询是否存在参数
     *
     * @param  string  $name
     * @return boolean
     */
    public function has($name)
    {
        return $this->get($name) === null;
    }

    /**
     * 删除参数<禁止删除>
     *
     * @param  string            $name
     * @throws \Formax\Exception
     */
    public function del($name)
    {
        throw new \Formax\Exception('This arguments can not be deleted');
    }

    /**
     * 以数组形态获取所有参数
     *
     * @return array
     */
    public function toArray()
    {
        return $this->dispatcher->getParams();
    }

    /**
     * 判断参数是否为空
     *
     * @return boolean
     */
    public function isEmpty()
    {
        $params = $this->dispatcher->getParams();

        return count($params['params']) === 0;
    }

    public function __set($name, $value)
    {
        return $this->set($name, $value);
    }

    public function __get($name)
    {
        return $this->get($name);
    }

    public function __isset($name)
    {
        return $this->has($name);
    }

    public function __unset($name)
    {
        return $this->del($name);
    }

    public function offsetExists($offset)
    {
        return $this->has($offset);
    }

    public function offsetGet($offset)
    {
        return $this->get($offset);
    }

    public function offsetSet($offset, $value)
    {
        return $this->set($offset, $value);
    }

    public function offsetUnset($offset)
    {
        return $this->del($name);
    }

}
